<template>
  <div>
    <cfg-table
      ref="table"
      :columns="columns"
      :data="data"
      :loading="loading"
      :config="config"
      :pageSizeOpts="pageSizeOpts"
      :pageNavigation="pageNavigation"
      :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem"
      :additionalAction="additionalAction"
      :btnShowFun="btnShowFun"
      @loadPage="loadPage"
      @handleCreate="handleCreate"
      @handleDetail="handleDetail"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    ></cfg-table>
    <new-add-modal
      v-bind="addNewPanel"
      :modelType="modelType"
      :columns="addFormColumns"
      :rules="rules"
      @submit="handleNewAddSubmit"
    ></new-add-modal>
    <single-modal v-bind="recordPanel" @submit="submitRecord">
      <cfgForm
        :cols="recordPanel.cols"
        :rules="rules"
        :columns="formColumns"
        ref="_frm"
        :data="recordPanel.data"
      ></cfgForm>
      <formRule
        ref="_formRule"
        :data="resultData"
        :cols="recordPanel.cols"
        :labelWidth="labelWidth"
        :columns="formMeterColumns"
      ></formRule>
    </single-modal>
    <read-modal
      v-bind="readPanel"
      :modelType="modelType"
      :columns="columns"
      :rules="rules"
    ></read-modal>
    <!-- 绑定设备 -->
    <bind-equip
      :equipPanel="equipPanel"
      :isSingleCheck="isSingleCheck"
      :selectionData="equipSelectionData"
      :selfSelectFilter="selfMeterSelectFilter"
      @submit="handleSelectSubmit"
    >
    </bind-equip>
  </div>
</template>

<script>
import newAddModal from "@/pages/components/newAddModal.vue";
import editModal from "@/pages/components/editModal.vue";
import readModal from "@/pages/components/readModal.vue";
import singleModal from "@/pages/components/singleModal.vue";
import formRule from "@/pages/components/formRule";
import { typeClassName } from "../../config/classNameMap";
import mixin from "@/pages/components/mixins/mixin";
import reviewMixin from "../mixins/reviewMixin";
import actionConditonMixin from "../mixins/actionConditonMixin";
import bindEquip from "@/pages/components/bindEquip.vue";
import bindEquipmentMixin from "../mixins/bindEquipmentMixin";
import columnsMixin from './config'
export default {
  components: {
    newAddModal,
    editModal,
    readModal,
    bindEquip,
    singleModal,
    formRule,
  },
  name: "energyEstimationOrder",
  mixins: [mixin, reviewMixin, actionConditonMixin, bindEquipmentMixin, columnsMixin],
  data() {
    return {
      classObject: null, // 单个实例
      collectionObject: null, // 所有实例
      className: typeClassName["energyEstimationOrder"].className,
      type: typeClassName["energyEstimationOrder"].type,
      modelType: typeClassName["energyEstimationOrder"].modelType,
      checkStatusClassObject: null,
      checkStatusOptions: [], // 审核状态
      equipSelectionData: [], // 绑定设备
      isSingleCheck: false,
      labelWidth: 120,
      // 进入页面需要的筛选条件：所属分类，'0'设备和'1'仪表
      selfMeterSelectFilter: { sf_category: "1" },
      addNewPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
      },
      recordPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
        data: {},
        title: "edit",
      },
      readPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 2,
        data: {},
      },
      equipPanel: {
        width: 1024,
        zIndex: 100,
        titleStyle: {},
        drawer: {
          show: false,
        },
        cols: 3,
        data: {},
      },
      rules: {
        sf_estimationOrderCode: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        if_estimationMonth: [
          {
            required: true,
            type: "number",
            message: "不能为空",
            trigger: "blur",
          },
        ],
      },
      loading: false,
      config: {
        search: true,
        addButton: true,
        batchDeleteButton: true,
        tableSizeIcon: true,
        fullscreenIcon: true,
        refreshIcon: false,
        columnSettingIcon: true,
        action: true,
        additionalAction: true,
      },
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
      view: "energyEstimationOrder",
      meterEstimationData: {},
      meterEstimation: [],
      resultData: {},
    };
  },
  computed: {
    additionalAction() {
      let additionalAction = {
        key: "additionalAction",
        title: {
          "zh-CN": "附加操作",
          "en-US": "additional action",
        }[this.G_Locale],
        slot: "additionalAction",
        width: 200,
        fixed: "right",
        align: "center",
        show: true,
        buttons: [
          {
            title: {
              "zh-CN": "绑定仪表",
              "en-US": "bind meter",
            }[this.G_Locale],
            event: (row, index) => this.bindEquipment(row, index),
          },
          { title: {
                'zh-CN': '审核',
                'en-US': 'review'
            }[this.G_Locale],
            key:'review',
            event: (row, index) => this.review(row, index)
          },
          { title: {
                'zh-CN': '反审',
                'en-US': 'reverse review'
            }[this.G_Locale],
            key:'reverseReview',
            event: (row, index) => this.reverseReview(row, index)
          }
        ],
      };
      this.G_IsMobile && (additionalAction.width = 90)
      return additionalAction;
    },
    data() {
      if (this.collectionObject) {
        return this.collectionObject.records.map((d) => {
          return {
            ...d,
            ...d.values,
          };
        });
      } else {
        return [];
      }
    },
  },
  beforeMount() {
    this.collectionObject = this.$modelObject.create(
      `${this.modelType}Collection`
    );
    this.classObject = this.$modelObject.create(this.modelType);
    this.checkStatusClassObject = this.$modelObject.create(
      typeClassName["checkStatus"].modelType
    );
    this.setOptions(
      "checkStatus",
      this.checkStatusClassObject,
      "checkStatusOptions"
    );
    this.loadPage(this.pageNavigation, null);
  },
  mounted() {},
  methods: {
    async handleEdit(row, index) {
      this.loading = true;
      if (await this.getRecord({type: row.type,className: row.className,id: row.id,})) {
         //是否有编辑弹框打开条件且满足
        if(!this.editPanelOpenCondition(this.classObject.record)){
             this.loading = false;
             return;
        }
        this.$set(this.recordPanel, "data", this.classObject.record.values);
        let originalData = [];
        this.meterEstimation = !this.classObject.record.values.meterEstimation ? []: this.tools.lodash.cloneDeep(this.classObject.record.values.meterEstimation);
        if (this.classObject.isValidHier()) {
          this.classObject.hier[0].basic.forEach((d) => {
            let index = this.meterEstimation.findIndex((item) => item.id == d.id);
            if (index !== -1) {
              originalData.push({id: d.id,value: this.meterEstimation[index].value,label: this.meterEstimation[index].label,});
              this.resultData[d.id] = this.meterEstimation[index].value
            } else {
              originalData.push({id: d.id,value: null,label: d.values["sf_name"],});
            }
          });
        }
        this.meterEstimation = originalData;
        this.$set(this.classObject.record.values,"meterEstimation",originalData);
        this.$set(this.recordPanel, "data", this.classObject.record.values);
        this.$set(this.recordPanel.drawer, "show", true);
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    submitRecord(data) {
      this.$refs._frm.$refs.form.validate((valid) => {
        if (valid) {
          Object.keys(this.resultData).map((d) => {
            let index = this.meterEstimation.findIndex((item) => item.id == d);
            if (index !== -1) {
              this.meterEstimation[index].value = this.resultData[d];
            }
          });
          this.$api.Custom.energyEstimation(this.classObject.record).then((flag) => {
              if (flag) {
                let index = this.collectionObject.records.findIndex((item) => item.id === this.classObject.record.id);
                if (index !== -1) {
                  this.collectionObject.records.splice(
                    index,
                    1,
                    this.classObject.record
                  );
                }
                this.$set(this.recordPanel.drawer, "show", false);
              }
            }
          );
        }
      });
    },
    // 删除+权限
    deleteRecord (ids) {
        // 仅删除 1、待审核状态且 2、本人数据
        if (this.isDeleteFlag(ids)) {
            return;
        }
        let _this = this;
        this.loading = true;
        return this.collectionObject.deleteByIds(ids).then((flag) => {
            if (flag) {
                ids.forEach((id) => {
                    let index = _this.collectionObject.records.findIndex(
                        (item) => item.id === id
                    );
                    if (index !== -1) {
                        _this.collectionObject.records.splice(index, 1);
                    }
                });
                this.loading = false;
                return true;
            } else {
                this.loading = false;
                return false;
            }
        });
    },
    /**
     * 编辑框打开条件
     * 已审批状态不可修改
     */
    editPanelOpenCondition(data){
        let flag = true;
        if (data.values['checkStatus'] === '审批通过' || this.classObject.record.values['checkStatus'] === '已审批') {
          flag = false;
          this.$Message.error('已审批状态不可修改')
        }
        return flag;
    },
    //审核反审按钮是否显示
    btnShowFun(row,btnKey){
        if(btnKey==='review' && (row.checkStatus === '审批通过' || !this.isPermissionPerson(row))){
            return false
        }else if(btnKey==='reverseReview' && (row.checkStatus !== '审批通过' && row.checkStatus !== '已审批' || this.getPersonAccount(row.checker)!== this.currentAccount.account)){
            return false
        }else{
            return true
        }
    },
  },
};
</script>
<style scoped lang="scss"></style>
